const Promise = require('bluebird')
const redis = Promise.promisifyAll(require('redis'))

class ChatService {
  constructor (prefix, maxlength) {
    this.rc = redis.createClient({ prefix })
    this.maxlength = maxlength || 5
  }

  async saveMessage (data) {
    await this.rc.lpushAsync('message', JSON.stringify(data))
    var length = await this.rc.llenAsync('message')
    if (length > this.maxlength) {
      await this.rc.ltrimAsync('message', 0, this.maxlength)
    }
  }

  async readMessage () {
    var res = await this.rc.lrangeAsync('message', 0, -1)
    return res.map(JSON.parse)
  }
}
module.exports = ChatService
